package cn.wolfcode.car.business.service.impl;


import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.domain.CarPackageAudit;
import cn.wolfcode.car.business.domain.ServiceItem;
import cn.wolfcode.car.business.mapper.CarPackageAuditMapper;
import cn.wolfcode.car.business.query.CarPackageAuditQuery;
import cn.wolfcode.car.business.service.IBpmnInfoService;
import cn.wolfcode.car.business.service.ICarPackageAuditService;
import cn.wolfcode.car.business.service.IServiceItemService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.common.util.Convert;
import cn.wolfcode.car.shiro.ShiroUtils;
import com.github.pagehelper.PageHelper;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.task.Task;
import org.activiti.image.ProcessDiagramGenerator;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.InputStream;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

//%test%

@Service
@Transactional
public class CarPackageAuditServiceImpl implements ICarPackageAuditService {

    @Autowired
    private CarPackageAuditMapper carPackageAuditMapper;

    @Autowired
    private RepositoryService repositoryService;

    @Autowired
    private IBpmnInfoService bpmnInfoService;

    @Autowired
    private IServiceItemService serviceItemService;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private TaskService taskService;


    @Override
    public TablePageInfo<CarPackageAudit> query(CarPackageAuditQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<CarPackageAudit>(carPackageAuditMapper.selectForList(qo));
    }


    @Override
    public void save(CarPackageAudit carPackageAudit) {
        carPackageAuditMapper.insert(carPackageAudit);
    }

    @Override
    public CarPackageAudit get(Long id) {
        return carPackageAuditMapper.selectByPrimaryKey(id);
    }


    @Override
    public void update(CarPackageAudit carPackageAudit) {
        carPackageAuditMapper.updateByPrimaryKey(carPackageAudit);
    }

    @Override
    public void deleteBatch(String ids) {
        Long[] dictIds = Convert.toLongArray(ids);
        for (Long dictId : dictIds) {
            carPackageAuditMapper.deleteByPrimaryKey(dictId);
        }
    }

    @Override
    public List<CarPackageAudit> list() {
        return carPackageAuditMapper.selectAll();
    }

    @Override
    public InputStream processImg(Long id) {

        CarPackageAudit carPackageAudit = carPackageAuditMapper.selectByPrimaryKey(id);
        if (carPackageAudit == null) {
            throw new BusinessException("参数异常");
        }
        BpmnInfo bpmnInfo = bpmnInfoService.get(carPackageAudit.getBpmnInfoId());
        if (bpmnInfo == null) {
            throw new BusinessException("参数异常");
        }
        BpmnModel model = repositoryService.getBpmnModel(bpmnInfo.getActProcessId());
        ProcessDiagramGenerator generator = new DefaultProcessDiagramGenerator();
        //generateDiagram(流程模型,需要高亮的节点,需要高亮的线条,后面三个参数都表示是字体)
        InputStream inputStream = null;


        if (!CarPackageAudit.STATUS_IN_ROGRESS.equals(carPackageAudit.getStatus())) {
            inputStream = generator.generateDiagram(model, Collections.EMPTY_LIST, Collections.EMPTY_LIST,
                    "宋体", "宋体", "宋体");
            return inputStream;
        }
        Task task = taskService.createTaskQuery().deploymentId(bpmnInfo.getDeploymentId()).singleResult();

        List<String> activeActivityIds = runtimeService.getActiveActivityIds(task.getExecutionId());
        inputStream = generator.generateDiagram(model, activeActivityIds, Collections.EMPTY_LIST,
                "宋体", "宋体", "宋体");

        return inputStream;

    }

    @Override
    public void cancelApply(Long id) {
        CarPackageAudit carPackageAudit = carPackageAuditMapper.selectByPrimaryKey(id);
        if (carPackageAudit == null) {
            throw new BusinessException("参数有误");
        }
        if (!CarPackageAudit.STATUS_IN_ROGRESS.equals(carPackageAudit.getStatus())) {
            throw new BusinessException("此状态下无法取消");
        }

        //撤销业务层
        carPackageAuditMapper.updateStatusById(id, CarPackageAudit.STATUS_CANCEL);
        ServiceItem serviceItem = serviceItemService.get(carPackageAudit.getServiceItemId());
        serviceItem.setSaleStatus(ServiceItem.AUDITSTATUS_INIT);

        //撤销activiti7
        runtimeService.deleteProcessInstance(carPackageAudit.getInstanceId(), "用户自行发起取消");

    }

    @Override
    public void audit(Long id, Integer auditStatus, String info) {
        if (id == null || auditStatus == null) {
            throw new BusinessException("参数有误");
        }
        CarPackageAudit carPackageAudit = carPackageAuditMapper.selectByPrimaryKey(id);
        if (carPackageAudit == null) {
            throw new BusinessException("参数有误");
        }

        carPackageAudit.setAuditTime(new Date());
        String newInfo=null;
        Task task = taskService.createTaskQuery().processInstanceId(carPackageAudit.getInstanceId()).taskAssignee(ShiroUtils.getUser().getId().toString()).singleResult();
        taskService.setVariable(task.getId(),"auditStatus",auditStatus);
        taskService.complete(task.getId());

        //审核通过
        if
        (CarPackageAudit.STATUS_PASS.equals(auditStatus)) {
            newInfo = carPackageAudit.getInfo()+"," + "[" + ShiroUtils.getUser().getUserName() + "同意" +","+info+"]";
            Task nextTask = taskService.createTaskQuery().processInstanceId(carPackageAudit.getInstanceId()).singleResult();



            if(nextTask==null){
                serviceItemService.setStatus(carPackageAudit.getServiceItemId(),ServiceItem.AUDITSTATUS_APPROVED);
                carPackageAudit.setStatus(auditStatus);
            }else {
                carPackageAudit.setAuditorId(Long.parseLong(nextTask.getAssignee()));
            }


        } else
            //审核拒绝
            if (CarPackageAudit.STATUS_REJECT.equals(auditStatus)) {
                serviceItemService.setStatus(carPackageAudit.getServiceItemId(),ServiceItem.AUDITSTATUS_INIT);
                carPackageAudit.setStatus(auditStatus);
                newInfo = carPackageAudit.getInfo()+"," + "[" + ShiroUtils.getUser().getUserName() + "拒绝" + "]";

            }

        carPackageAudit.setInfo(newInfo);
            carPackageAuditMapper.updateByPrimaryKey(carPackageAudit);
    }



}
